<?php
namespace Apps\AppApi\Method\BeautyCanon;

use Apps\AppApi\Method\BaseMethod;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\CosBeautyCanonAssist;
use Apps\Common\Models\CosBeautyCanon;
use PhalconPlus\Api\Models\ApiUserAuth;
/**
 * 美粒宝典点赞
 * @author      545
 * @date        2016年1月18日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class BcAssist extends BaseMethod{
	private $success = 0;
	private $assist = 0;
	
	public function run(){
	    
	    //验证登录
	    if(false == $this->verifyUserAuth()){
	        return false;
	    }
	    $userId = $this->getUserAuth()->userId;
		$bc_id = intval($this->getDataItem('bc_id',0));		
		if($bc_id > 0){
			$bc_info = CosBeautyCanon::findFirst("id = $bc_id and state != 3");
			if($bc_info){
				//判断是否已经点过赞
				$bc_assist = CosBeautyCanonAssist::count([
						"conditions"=>"user_id = :sign: AND beauty_canon_id = :bc_id: ",
						"bind" => [
								'sign' => $userId,
								'bc_id' => $bc_id,
						],
				]);
				if($bc_assist > 0){
					$query = CosBeautyCanon::findFirst("id = $bc_id") -> toArray();
					$this -> assist = intval($query['assist']);
					$this -> success = 2;
				}else{
					//记录点赞
					$model = new CosBeautyCanonAssist();
					$model -> user_id = $userId;
					$model -> beauty_canon_id = $bc_id;
					$model -> setdate = date("Y-m-d H:i:s",time());
					if($model -> save()){
						$this -> updateAssist($bc_id);
						$query = CosBeautyCanon::findFirst("id = $bc_id") -> toArray();
						$this -> assist = intval($query['assist']);
						$this -> success = 1;
					}else{
						return $this->databaseErrorLog($model);
					}
				}
				$this->setResult(["success" => $this->success,"assist" => $this -> assist]);
			}else{
				return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "该美粒宝典不存在！");
			}
			
		}else{
			return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "");
		}
	}
	
	/*
	 *更新美粒宝典点赞数
	 */
	public static function updateAssist($id)
	{
		$sql = 'UPDATE beauty_canon SET assist = assist+1 WHERE id = :bc_id';
		$model = new CosBeautyCanon();
		return $model->getWriteConnection()->execute($sql, ['bc_id' => $id]);
	}
	
} 